package com.zrt.pad.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.accounts.NetworkErrorException;
import android.util.Log;


public class Network {

	public static final Network instance = new Network();

	private Network() {

	}
	/**
	 * 设置默认超时为40秒
	 */
	public static int timeOut = 40;

	public String get(String url, String args) throws NetworkErrorException {
		if (!url.endsWith("/")) {
			url += "/";
		}
		if (args != null) {
			url += args;
		}
		Log.d("network", "get url:"+url);
		HttpGet get = new HttpGet(url);
		//set header
		get.setHeader(HTTP.CONTENT_TYPE, "text/json");
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut * 1000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeOut * 1000);
		HttpResponse response = null;
		try {
			response = client.execute(get);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (response == null) {
			throw new NetworkErrorException("网络异常，无法建立连接！");
		}
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			StringBuffer buffer = new StringBuffer();
			try {
				InputStream is = response.getEntity().getContent();
				InputStreamReader isr = new InputStreamReader(is, "UTF-8");
				BufferedReader br = new BufferedReader(isr);
				String line = br.readLine();
				while (line != null) {
					buffer.append(line);
					line = br.readLine();
				}
				br.close();
				isr.close();
				is.close();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return buffer.toString();
		} else {
			String msg = "Http Error:"+response.getStatusLine().getStatusCode()+";Reason:"+response.getStatusLine().getReasonPhrase();
			throw new NetworkErrorException(msg);
		}
	}
	
	
	public String post(String url, List<NameValuePair> args) throws NetworkErrorException{
		Log.d("network", "post url:"+url);
		HttpPost post = new HttpPost(url);
		if (args != null && args.size() > 0) {
			try {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(args, "UTF-8");
				post.setEntity(entity);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		post.setHeader(HTTP.CONTENT_TYPE, "text/json");
		post.setHeader("Accept", "application/json");
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut * 1000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeOut * 1000);
		HttpResponse resp = null;
		try {
			resp = client.execute(post);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (resp == null) {
			throw new NetworkErrorException("网络异常，无法建立连接！");
		}
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			StringBuffer buffer = new StringBuffer();
			try {
				InputStream is = resp.getEntity().getContent();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = br.readLine();
				while(line != null){
					buffer.append(buffer);
					line = br.readLine();
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return buffer.toString();
		}
		throw new NetworkErrorException("Http Error:"+resp.getStatusLine().getStatusCode()+";Reason:"+resp.getStatusLine().getReasonPhrase());
	}
	
	public String post(String url, JSONObject args) throws NetworkErrorException {
		return post(url, args.toString());
	}
	
	public String post(String url, String args) throws NetworkErrorException {
		Log.d("network", "post url:"+url);
		HttpPost post = new HttpPost(url);
		try {
			post.setEntity(new StringEntity(args, "utf-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
	
		post.setHeader(HTTP.CONTENT_TYPE, "text/json");
		post.setHeader("Accept", "application/json");
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut * 1000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeOut * 1000);
		HttpResponse resp = null;
		try {
			resp = client.execute(post);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (resp == null) {
			throw new NetworkErrorException("网络异常，无法建立连接！");
		}
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			StringBuffer buffer = new StringBuffer();
			try {
				InputStream is = resp.getEntity().getContent();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = br.readLine();
				while(line != null){
					buffer.append(line);
					line = br.readLine();
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return buffer.toString();
		}
		throw new NetworkErrorException("Http Error:"+resp.getStatusLine().getStatusCode()+";Reason:"+resp.getStatusLine().getReasonPhrase());
	}
	/**
	 * 使用反射机制解析传进来的对象，封装成K（属性名）V（属性值） 的HashMap 由于继承封装的关系，只能解析出所有的public修饰的属性值
	 * 
	 * @param o
	 *            要解析的参数
	 * @return 封装好的HashMap 如果o为null，则直接返回null
	 */
	public HashMap<String, String> parseArgumentObject(Object o) {
		if (o == null) {
			return null;
		}
		HashMap<String, String> map = new HashMap<String, String>();
		Class<?> c = o.getClass();
		Field[] fields = c.getDeclaredFields();
		try {
			for (Field f : fields) {
				map.put(f.getName(), f.get(o).toString());
			}
		} catch (IllegalAccessException e) {
		} catch (IllegalArgumentException e) {
		}
		return map;
	}



}
